package de.gameduell.net.src.connection {
	import flash.net.URLRequestMethod;
	import de.gameduell.net.src.communication.Communication;	
	
	import flash.events.SecurityErrorEvent;	
	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLVariables;
	
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.util.LockManager;
	import de.gameduell.net.src.communication.CommunicationEvent;
	import de.gameduell.net.src.communication.ICommunication;
	import de.gameduell.net.src.connection.IConnection;
	import de.gameduell.net.src.message.IMessage;
	
	import flash.events.IOErrorEvent;	

	public class LoadVarsConnection extends EventDispatcher implements IConnection {
	
		public static const CONNECTION_TYPE:String = "loadvars";
		private const DEFAULT_TARGET:String        = "/gs-bin/v3.cgi";
		
		private var request:URLRequest;
		private var variables:URLVariables;
		private var lockManager:LockManager;
		private var active:Boolean;
		private var isOnline:Boolean = false;
		private var _used:Boolean    = false;
		
		protected var communication:ICommunication;

		public function LoadVarsConnection(aCommunication:ICommunication) {
			lockManager    = LockManager.getInstance(); 
			communication  = aCommunication;		
			variables 	   = new URLVariables();
			active         = true;
		}

		public function sendMessage(message:IMessage):void {
			if(active){
				variables.sendString = message.encryptedContent;
				request.data = variables;
				var loader:URLLoader = new URLLoader();
				loader.addEventListener(Event.COMPLETE, dataLoaded);
				loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
				try{
					log("sendMessage " + message.content, Debug.SEND);
					loader.load(request);
				}catch (error:Error){
	                log("sendMessage: A SecurityError has occurred. error: " + error, Debug.ERROR);
	            }
			}
		}
		
		private function onSecurityError(event:SecurityErrorEvent):void {
			log("onSecurityError: SecurityErrorEvent -> " + event, Debug.ERROR);
		}

		private function errorHandler(event:IOErrorEvent):void {
			log("errorHandler: IOErrorEvent -> " + event, Debug.ERROR);
		}

		private function dataLoaded(event:Event):void {
			log("dataLoaded");
			_used = true;
			if(!isOnline){
				isOnline = true;
				dispatchEvent(new CommunicationEvent(CommunicationEvent.CONNECTED));
			}
			var rawData:String = String(event.currentTarget.data);
			var loadString:String = rawData.slice(11, rawData.length);
			dispatchEvent(new DataEvent(DataEvent.DATA, false, false, loadString));
		}
		
		public function connect(host:String, port:int):void {
			if(active){
				request = new URLRequest("http://" + host + DEFAULT_TARGET);
				request.method = URLRequestMethod.POST;
			}
		}
		
		public function close():void {
			active = false;
		}
		
		public function stopConnectTimer():void {
		}
		
		public function getType():String {
			return CONNECTION_TYPE;
		}
		
		public function reconnect(host:String, port:int):void {
			isOnline = false;
			connect(host, port);
		}
		
		public function get used():Boolean {
			return _used;
		}
		
		private function log(aMessage:String, logMode:String = Debug.DEBUG):void{
			if(Communication.DEBUG_ENABLED || logMode == Debug.ERROR){
				Debug.trace("LoadVarsConnection::" +  aMessage, logMode);
			}
		} 
	}
}
